import { reqShopCart, delShopCartItem, changeChecked } from '@/api/index'

const state = {
    shopCart: [{}]
};
const mutations = {
    GETSHOPCARTINFO(state, shopCart) {
        state.shopCart = shopCart
    }
};
const actions = {
    async getShopCartInfo({ commit }) {
        let res = await reqShopCart();
        if (res.code == 200) {
            console.log('购物车数据获取成功');
            commit('GETSHOPCARTINFO', res.data)
        } else {
            console.log('购物车数据获取失败,' + res.message);
        }
    },
    async delShopCartItem({ commit }, skuId) {
        let res = await delShopCartItem(skuId);
        if (res.code == 200) {
            return '删除成功!';
        } else {
            return Promise.reject(new Error('删除失败!'))
        }
    },
    async changeChecked({ commit }, { skuId, checked }) {
        let res = await changeChecked(skuId, checked);
        if (res.code == 200) {
            return '修改成功!';
        } else {
            return Promise.reject(new Error('修改失败!'))
        }
    },

    // 怎么在actions的函数中调用action的函数???
    // 批量删除
    deleteAllItemChecked(context) {
        // context:包括commit/getters/dispatch/state,可以利用它来操作仓库
        // 获取购物车中全部的产品
        let promises = [];
        context.getters.cartInfoList.forEach(async function(item) {
            // 获取删除操作返回的promise对象
            if (item.isChecked == 1) {
                let promise = context.dispatch('delShopCartItem', item.skuId);
                promises.push(promise);
            }
        })
        return Promise.all(promises);
    },

    // 全选/全部选
    AllItemChecked(context, isChecked) {
        let promises = [];
        context.getters.cartInfoList.forEach(async function(item) {
            // 获取删除操作返回的promise对象
            if (item.isChecked != isChecked) {
                // 如果item的checked与全选状态相同,就不用修改了
                let promise = context.dispatch('changeChecked', { skuId: item.skuId, checked: isChecked });
                promises.push(promise);
            }
        })
        return Promise.all(promises);
    }
};
const getters = {
    cartInfoList(state) {
        if (state.shopCart.length == 0)
            return []
        return state.shopCart[0].cartInfoList || [];
    }

};

export default {
    state,
    mutations,
    actions,
    getters
}